package com.liu.jdbc.dao_.dao;

import com.liu.jdbc.dao_.utils.JDBCUtilsByDruid;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.sql.Connection;
import java.util.List;

public class BasicDao <T> {
    private  QueryRunner qr = new QueryRunner();
    //开发通用的dml 操作
    public int update(String sql, Object... parameters) {
        Connection conn = null;
        try {
            conn = JDBCUtilsByDruid.getConnection();
            int update = qr.update(conn, sql, parameters);
            return update;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally{
            JDBCUtilsByDruid.close(null,null,conn);
        }
    }
    //返回多个查询
    public List<T> queryMulti(String sql,Class<T> clazz ,Object... parameters) {
        Connection conn = null;
        try {
            conn = JDBCUtilsByDruid.getConnection();
           return qr.query(conn,sql,new BeanListHandler<T>(clazz),parameters);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally{
            JDBCUtilsByDruid.close(null,null,conn);
        }
    }
    //查询单个查询
    public T querySingle(String sql,Class<T> clazz, Object... parameters) {
        Connection conn = null;
        try {
            conn = JDBCUtilsByDruid.getConnection();
            return qr.query(conn,sql,new BeanHandler<T>(clazz),parameters);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally{
            JDBCUtilsByDruid.close(null,null,conn);
        }
    }
    //查询单行单列
    public Object queryScalar(String sql, Object... parameters) {
        Connection conn = null;
        try {
            conn = JDBCUtilsByDruid.getConnection();
            return qr.query(conn,sql,new ScalarHandler(),parameters);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally{
            JDBCUtilsByDruid.close(null,null,conn);
        }
    }
}
